<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2018 http://www.donglixia.net All rights reserved.
// +----------------------------------------------------------------------
// | Author: 十万马 <962863675@qq.com>
// +----------------------------------------------------------------------
// | DateTime: 2018-02-09 16:17
// +----------------------------------------------------------------------

namespace app\admin_fussen\controller;

use app\admin_fussen\model\Goods as GoodsModel;
use app\admin_fussen\model\BasicInfo as BasicInfoModel;
use app\admin_fussen\model\GoodsExtCat;
use think\Db;
use think\Request;
use think\Session;

class Goods extends Base
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->currentModel = new GoodsModel();//实例化当前模型
    }

    /**
     * 列表页
     * @return mixed
     */
    public function index()
    {
        /*获取产品推荐等级*/
        $BasicInfo = new BasicInfoModel();
        $levelList = $BasicInfo->getBasicList('goods', 'AA');
        $this->assign('levelList' ,$levelList);
        return $this->fetch();
    }

    /**
     * 列表页，获取数据
     * @return mixed
     */
    public function getDataList()
    {
        $map = $this->getDataListMap();
        return $this->currentModel->where($map)->order('sort_num asc, goods_id desc')->layTable(['cat_name','level_text','years_text','public_date']);
    }

    private function getDataListMap()
    {
        $param = $this->request->param();
        if (!empty($param['cat_id'])) {
            $map['cat_id'] = $param['cat_id'];//类目
        }
        if (!empty($param['goods_name'])) {
            $map['goods_name'] = ['like', '%' . $param['goods_name'] . '%'];//产品名称
        }
        if (!empty($param['level'])) {
            $map['level'] = $param['level'];//推荐等级
        }
        if (!empty($param['public_begin']) && !empty($param['public_end'])) {
            $map['public_time'] = ['between', [strtotime($param['public_begin']),strtotime($param['public_end'])]];//公布时间
        }

        $map['language'] = Session::get('config.language');
        return $map;
    }
    
    public function edit()
    {
        $param = $this->request->param();
        $goods_id = !empty($param['goods_id']) ? $param['goods_id'] : '';
        if (!empty($goods_id)) {
            //获取当前产品信息
            $data = $this->currentModel->where('goods_id', $goods_id)->field(true)->field('public_time as public_date_hh_ii_ss')->find();
            if (empty($data)) {
                $this->error('信息不存在');
            }
            $data = $data->toArray();
            $this->assign('data', $data);
        }

        //获取产品推荐等级
        $BasicInfo = new BasicInfoModel();
        $levelList = $BasicInfo->getBasicList('goods', 'AA');
        $this->assign('levelList' ,$levelList);

        //获取“系列”列表
        $curr_cat_id = !empty($data['cat_id']) ? $data['cat_id'] : 0;
        $seriesList = $this->currentModel->getCatOptionTree(['cat_type'=>197], $curr_cat_id);
        $this->assign('seriesList', $seriesList);

        //获取“国家”列表
        $curr_cat_id = !empty($data['country']) ? $data['country'] : 0;
        $countryList = $this->currentModel->getCatOptionTree(['cat_type'=>198], $curr_cat_id);
        $this->assign('countryList', $countryList);

        //获取“年份”列表
        $curr_cat_id = !empty($data['years']) ? $data['years'] : 0;
        $YearsList = $this->currentModel->getCatOptionTree(['cat_type'=>199], $curr_cat_id);
        $this->assign('yearsList', $YearsList);

        //获取扩展栏目下拉列表
        $curr_cat_ext = !empty($data['goods_id']) ? Db::name('goods_ext_cat')->where('goods_id', $data['goods_id'])->column('cat_id') :[];
        $catExtList = $this->currentModel->getCatExtOptionTree([], $curr_cat_ext);
        $this->assign('catExtList' , $catExtList);

        return $this->fetch();
    }

    /**
     * 保存
     */
    public function save()
    {
        $param = $this->request->param();
        if (empty($param)) {
            $this->error('没有需要保存的数据！');
        }
        //默认排序为1
        $param['sort_num'] = !empty($param['sort_num']) ? $param['sort_num'] : 1;
        //验证数据
        $result = $this->validate($param, 'Goods');
        if ($result !== true) {
            $this->error($result);
        }
        try{
            //主有变更，从临时文件夹移动图片，并生成缩略图
            if (!empty($param['img_url'])) {
                $old = !empty($param['goods_id']) ? Db::name('goods')->where('goods_id', $param['goods_id'])->field('img_url,img_url_thumb')->find() : '';
                if (empty($old) || $param['img_url'] != $old['img_url']) {
                    $param['img_url'] = current(imgTempFileMove([$param['img_url']], 'admin_fussen/images/goods/'));//从临时文件夹移动图片
                    $param['img_url_thumb'] = str_replace('.', '_thumb.', $param['img_url']);
                    \tp_tools\Image::open(PUBLIC_PATH . $param['img_url'])->thumb(310, 310)->save(PUBLIC_PATH . $param['img_url_thumb'], null, 100);//透明底
                    if (!empty($param['goods_id'])) {
                        $count = Db::name('goods')->where('img_url', $old['img_url'])->count();//编辑且换图，则删除旧图片
                        //若其他地方没使用该旧图片，则删除
                        if ($count == 1){
                            delete_file($old['img_url']);
                            delete_file($old['img_url_thumb']);
                        }
                    }
                }
            }

            //详情图片有变更，从临时文件夹移动图片
            if (!empty($param['detail_img'])) {
                $old = !empty($param['goods_id']) ? Db::name('goods')->where('goods_id', $param['goods_id'])->field('detail_img')->find() : '';
                if (empty($old) || $param['detail_img'] != $old['detail_img']) {
                    $param['detail_img'] = current(imgTempFileMove([$param['detail_img']], 'admin_fussen/images/goods/'));//从临时文件夹移动图片
                    if (!empty($param['goods_id'])) {
                        $count = Db::name('goods')->where('detail_img', $old['detail_img'])->count();//编辑且换图，则删除旧图片
                        //若其他地方没使用该旧图片，则删除
                        if ($count == 1){
                            delete_file($old['detail_img']);
                        }
                    }
                }
            }

            //详情图片有变更，从临时文件夹移动图片
            if (!empty($param['area_img'])) {
                $old = !empty($param['goods_id']) ? Db::name('goods')->where('goods_id', $param['goods_id'])->field('area_img')->find() : '';
                if (empty($old) || $param['area_img'] != $old['area_img']) {
                    $param['area_img'] = current(imgTempFileMove([$param['area_img']], 'admin_fussen/images/goods/'));//从临时文件夹移动图片
                    if (!empty($param['goods_id'])) {
                        $count = Db::name('goods')->where('area_img', $old['area_img'])->count();//编辑且换图，则删除旧图片
                        //若其他地方没使用该旧图片，则删除
                        if ($count == 1){
                            delete_file($old['area_img']);
                        }
                    }
                }
            }
            $this->currentModel->save($param);

            if (isset($param['cat_id_ext'])) {
                $GoodsExtCat = new GoodsExtCat();
                $GoodsExtCat->where('goods_id', $this->currentModel->goods_id)->delete();

                $cat_ext = [];
                $cat_id_arr = explode(',', $param['cat_id_ext']);
                foreach ($cat_id_arr as $k=>$v) {
                    if (!empty($v)) {
                        $cat_ext[$k]['goods_id'] = $this->currentModel->goods_id;
                        $cat_ext[$k]['cat_id'] = $v;
                    }
                }
                if (!empty($cat_ext)) {
                    $GoodsExtCat->saveAll($cat_ext);
                }
            }
        } catch (\Exception $e) {
            $msg = !empty($this->currentModel->getError()) ? $this->currentModel->getError() : $e->getMessage();
            save_error_log($msg.' ['.$e->getFile().':'.$e->getLine().']');
            $this->error($msg);
        }

        $this->success('保存成功！', 'edit?goods_id='.$this->currentModel->goods_id);
    }

    /**
     * 更改排序
     */
    public function changeSort()
    {
        $param = $this->request->param();
        if (empty($param['id']) || empty($param['type'])) {
            $this->error('参数错误');
        }

        try {
            $table_name = $this->currentModel->getTableName();//获取表名
            $list = reset_sort($param['id'], $table_name, $param['type'], 'sort_num', 'cat_id');//格式化，获取重新排序的数据
            $this->currentModel->saveAll($list);//保存数据
        } catch (\Exception $e) {
            $mag = $this->currentModel->getError() ? $this->currentModel->getError() : $e->getMessage();
            save_error_log($mag);
            $this->error($mag);
        }

        $this->success('操作成功');
    }

}

